// 首先，确保已经安装了pinia库。如果没有，请运行以下命令进行安装：
// npm install pinia
//封装购物车模块
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import { useUserStore } from './user';
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //state
    const cartList = ref([])
    //action
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (isLogin.value) {
            //登录后的加入口购物车
            await insertCartAPI({ skuId, count })
            updateNewList()
        } else {
            const item = cartList.value.find(item => goods.skuId === item.skuId)
            if (item) {
                item.count++
            } else {
                cartList.value.push({ ...goods, count: 1 })
            }
        }

    }
    //删除
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            updateNewList()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }

    }
    //清除购物车数据
    const clearCart =()=>{
        cartList.value=[]
    }
    //获取最新购物车列表action
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }
    //单选功能
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    //总数量计算
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    //总价计算
    const formattedAllPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    const allPrice = computed(() => formattedAllPrice.value.toFixed(2))

    //是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    //全选功能
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }
    //已选择商品数量
    const selectedCount = computed(() =>
        cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    )
    //已选择商品合计 
    const selectedPrice = computed(() =>
        cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    )
    return {
        updateNewList,
        clearCart,
        selectedPrice,
        selectedCount,
        allCheck,
        isAll,
        singleCheck,
        allCount,
        allPrice,
        cartList,
        addCart,
        delCart
    }

},
    {
        persist: true
    }
)

